﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMSGSC.Common;
using DevExpress.XtraEditors;
using PMSGSC.DAL;
using PMSGSC.BLL;
using System.IO;
using System.Data.Linq;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTab;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Localization;
namespace PMSGSC.App
{
    public partial class frmNewJob : DevExpress.XtraEditors.XtraForm
    {
        private int iEquipmentID;
        private Job objJob = new Job();
        private bool isJobChanged;
        private  bool isChangedA;
        private  bool isChangedAJ;

        public frmNewJob(int EquipmentID, int JobID)
        {
            InitializeComponent();

            if (JobID == 0)
            {
                objJob = jobBindingSource.AddNew() as Job;
                iEquipmentID = EquipmentID;
                ucLoadJobDescription1.id = EquipmentID;

                objJob.TimeUnit = "Hour(s)";
                objJob.TimeDone = 0;
                objJob.SC_ID = 2;
                objJob.Equipment_ID = iEquipmentID;
            }
            else
            {
                objJob = Job_BLL.GetDataById(JobID);
                jobBindingSource.Add(objJob);
                ucLoadJobDescription1.SetValue(objJob.JobDescription.CodeJD, objJob.JobDescription.NameJD, objJob.JobDescription_ID.ToString());
            }

            nextDueDateEdit1.Enabled = false;
            serviceCodeBindingSource.DataSource = ServiceCode_BLL.GetAll(frmMain.ship.Ship_ID);
            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);

            Job j = jobBindingSource.Current as Job;
            jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(j.Job_ID, false);
            attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(j.Job_ID, isChangedAJ);
            partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(objJob.Equipment_ID.Value, isChangedA);


            ShowTimeUnitCombo();
            LoadDataIntoTabPageJob();
        }
        private int GetLastTwoNumber(int year)
        {
            return year % 1000;
        }

        private void SetValueInsertJob(Job j)
        {
            if (freodicFrequencyTextEdit1.ContainsFocus && freodicFrequencyTextEdit1.Text != "")
                j.FreodicFrequency = int.Parse(freodicFrequencyTextEdit1.Text);

            if (lastDoneDateEdit1.ContainsFocus && lastDoneDateEdit1.Text != "")
                j.LastDone = lastDoneDateEdit1.DateTime.Date;

            if (timeDoneTextEdit1.ContainsFocus && timeDoneTextEdit1.Text != "")
                j.TimeDone = int.Parse(timeDoneTextEdit1.Text);

            if (alarmDaybeforeTextEdit1.ContainsFocus && alarmDaybeforeTextEdit1.Text != "")
                j.AlarmDaybefore = int.Parse(alarmDaybeforeTextEdit1.Text);

            if (cbbTimeUnit.ContainsFocus)
                j.TimeUnit = cbbTimeUnit.Text;

            if (ucRichEditControl1.isChange)
            {
                j.Details = ucRichEditControl1.richEditControl1.Text;
            }
        }

        public void SaveNewJob()
        {
            if (isJobChanged)
            {
                if (ucLoadJobDescription1.lbid.Text == "")
                {
                    XtraMessageBox.Show("Job Description not empty", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));
                thread.Start();
                SetValueInsertJob(objJob);
                objJob.JobDescription = BaseDAL.DB.JobDescriptions.Single(n => n.JobDescription_ID == int.Parse(ucLoadJobDescription1.lbid.Text));
                if (objJob.TimeUnit == "Hour(s)")
                {
                    objJob.Counter = true;

                    objJob.LastDone = null;
                    objJob.NextDue = null;
                    objJob.AlarmDaybefore = null;
                }
                else
                {
                    if (objJob.LastDone != null && objJob.FreodicFrequency != null)
                    {
                        objJob.NextDue = NextDue(objJob.FreodicFrequency.Value.ToString(), objJob.LastDone.Value);
                    }
                    objJob.Counter = false;
                    objJob.TimeDone = null;
                }
                if (objJob.Job_ID == 0)
                {
                    bool result = Job_BLL.Insert(objJob);
                    objJob = Job_BLL.GetLastJob();

                    WorkOrder newWorkOrder = new WorkOrder();
                    newWorkOrder.CreateDate = DateTime.Now.Date;
                    newWorkOrder.Detail = objJob.Details;
                    newWorkOrder.EmployeeCreate= frmMain.UserLogin.Name;
                    newWorkOrder.Equipment_ID = objJob.Equipment_ID.Value;
                    newWorkOrder.Frequency = objJob.FreodicFrequency;
                    newWorkOrder.IsCheck = false;
                    newWorkOrder.LastDone = objJob.LastDone;
                    newWorkOrder.Job_ID = objJob.Job_ID;
                    newWorkOrder.RespDescipline_ID = objJob.Employee_ID;
                    newWorkOrder.SC_ID = objJob.SC_ID;
                    newWorkOrder.Ship_ID = objJob.Equipment.Ship_ID;
                    newWorkOrder.StatusJob_ID = 1;
                    newWorkOrder.TimeUnit = objJob.TimeUnit;
                    newWorkOrder.Title = objJob.JobDescription.CodeJD + "-" + objJob.JobDescription.NameJD;
                    newWorkOrder.Type = 1;
                    newWorkOrder.Complete = false;
                    newWorkOrder.WorkOrderNumber = frmMain.ship.CodeShip + "/"+ DateTime.Now.Date.Year + "/" + WorkOrder_BLL.GetQuantityWorkOrder(frmMain.ship.Ship_ID).ToString("00000");

                    if (objJob.TimeUnit == "Hour(s)")
                    {
                        newWorkOrder.NextDue = null;
                        newWorkOrder.AlarmDaybefore = null;
                        newWorkOrder.TimeDone = objJob.TimeDone;
                    }
                    else
                    {

                        newWorkOrder.TimeDone = null;
                        newWorkOrder.NextDue = objJob.NextDue;
                        newWorkOrder.AlarmDaybefore = objJob.AlarmDaybefore;
                    }
                    WorkOrder_BLL.Insert(newWorkOrder);
                }
                else
                {
                    Job_BLL.Update(objJob);
                    WorkOrder oldWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(objJob.Job_ID);
                    if (oldWorkOrder != null)
                    {
                        oldWorkOrder.Title = objJob.JobDescription.CodeJD + "-" + objJob.JobDescription.NameJD;
                        oldWorkOrder.Frequency = objJob.FreodicFrequency;
                        oldWorkOrder.TimeUnit = objJob.TimeUnit;
                        if (objJob.TimeUnit == "Hour(s)")
                        {
                            oldWorkOrder.NextDue = null;
                            oldWorkOrder.AlarmDaybefore = null;
                            oldWorkOrder.TimeDone = objJob.TimeDone;
                        }
                        else
                        {
                            oldWorkOrder.TimeDone = null;
                            oldWorkOrder.NextDue = objJob.NextDue;
                            oldWorkOrder.AlarmDaybefore = objJob.AlarmDaybefore;
                        }
                        WorkOrder_BLL.Update(oldWorkOrder);
                    }
                }

                foreach (JobPart part in jobPartBindingSource.Cast<JobPart>().ToList())
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(objJob.Job_ID);
                    PartWorkOrder partWorkOrder = new PartWorkOrder();
                    if (objWorkOrder != null)
                    {
                        partWorkOrder.Parts_ID = part.Parts_ID;
                        partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                        partWorkOrder.Quantity = part.Quantity;
                    }

                    if (part.Job_ID == 0)
                    {
                        part.Job_ID = objJob.Job_ID;
                        PartJob_BLL.Insert(part);
                        //
                        PartWorkOrder_BLL.Insert(partWorkOrder);
                    }
                    else
                    {
                        PartJob_BLL.Update(part);
                        //
                        PartWorkOrder_BLL.Update(partWorkOrder);
                    }
                }

                foreach (AttachmentsJob attach in attachmentsJobBindingSource.Cast<AttachmentsJob>().ToList())
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(objJob.Job_ID);
                    AttachmentWorkOrder attachWorkOrder = new AttachmentWorkOrder();

                    if (objWorkOrder != null)
                    {
                        attachWorkOrder.Code = attach.Code;
                        attachWorkOrder.Name = attach.Name;
                        attachWorkOrder.ContentFile = attach.ContentFile;
                        attachWorkOrder.Extension = attach.Extentsion;
                        attachWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                    }
                    if (attach.Attachment_ID == 0)
                    {
                        attach.Job_ID = objJob.Job_ID;
                        AttachmentJob_BLL.Insert(attach);
                        AttachmentsJob att = AttachmentJob_BLL.GetLastData();
                        attachWorkOrder.AttachmentJob_ID = att.Attachment_ID;

                        AttachmentWorkOrder_BLL.Insert(attachWorkOrder);
                    }
                    else
                    {
                        AttachmentJob_BLL.Update(attach);
                        //
                        AttachmentWorkOrder_BLL.Update(attachWorkOrder);
                    }
                }
                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
                isJobChanged = false;
                this.Close();
            }
        }

        #region Job
        private void xtraTabControl5_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            LoadDataIntoTabPageJob();
           
        }

        private void LoadDataIntoTabPageJob()
        {
            XtraTabPage tabpage = xtraTabControl5.SelectedTabPage;
            Job j = jobBindingSource.Current as Job;
            if (j != null)
            {  
                switch (tabpage.Name)
                {
                    case "RP":
                      //  
                       
                        isChangedA = false;
                        break;
                    case "AJ":
                     //   
                        isChangedAJ = false;
                        break;
                }
            }
            else
            {
                switch (tabpage.Name)
                {
                    case "RP":
                       // jobPartBindingSource.DataSource = null;
                        break;
                    case "AJ":
                      //  attachmentsJobBindingSource.DataSource = null;
                        break;
                }

            }
        }

        private void ShowTimeUnitCombo()
        {
            if (objJob != null)
                cbbTimeUnit.SelectedIndex = GetIndexInCombobox(objJob.TimeUnit);
            else
                cbbTimeUnit.SelectedIndex = 0;
        }

        private int GetIndexInCombobox(string value)
        {
            if (value == "Hour(s)")
                return 0;
            if (value == "Day(s)")
                return 1;
            if (value == "Week(s)")
                return 2;
            return 3;
        }

        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        private int GetIndexJobDesCription(string code)
        {
            List<JobDescription> jd = jobDescriptionBindingSource.Cast<JobDescription>().ToList();
            foreach (JobDescription j in jd)
            {
                if (j.CodeJD == code)
                {
                    return j.JobDescription_ID;
                }
            }
            return -1;
        }

        private void txtCodeJob_EditValueChanged(object sender, EventArgs e)
        {

        }

        private DateTime NextDue(string Frequency, DateTime LastDone)
        {

            int Number = int.Parse(Frequency);
            DateTime dt = LastDone;
            switch (cbbTimeUnit.SelectedIndex)
            {
                case 1:
                    dt = dt.AddDays(Number);
                    break;
                case 2:
                    int NumberDay = Number * 7;
                    dt = dt.AddDays(NumberDay);
                    break;
                case 3:
                    dt = dt.AddMonths(Number);
                    break;
            }
            return dt;
        }

        private void CheckByTrue()
        {
            timeDoneTextEdit1.Enabled = true;

            lastDoneDateEdit1.Enabled = false;
            alarmDaybeforeTextEdit1.Enabled = false;
        }

        private void CheckByFasle()
        {
            timeDoneTextEdit1.Enabled = false;

            lastDoneDateEdit1.Enabled = true;
            alarmDaybeforeTextEdit1.Enabled = true;
        }

        private bool TestJobDescrExits(int id, int jobID)
        {
            List<Job> listJob = Job_BLL.GetDataByEquipmentID(objJob.Equipment_ID.Value,frmMain.ship.Ship_ID, false);
            foreach (Job j in listJob)
            {
                if (j.JobDescription_ID == id && j.Job_ID != jobID)
                {
                    return true;
                }
            }
            return false;

        }

        private void jobDescription_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (TestJobDescrExits((int)e.NewValue, objJob.Job_ID))
            {
                e.NewValue = e.OldValue;
                XtraMessageBox.Show("The value has been exitsed", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            try
            {
                objJob.JobDescription = BaseDAL.DB.JobDescriptions.Single(c => c.JobDescription_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void jobBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isJobChanged = true;
        }

        private void cbbTimeUnit_TextChanged(object sender, EventArgs e)
        {
            if (cbbTimeUnit.Text == "Hour(s)")
            {
                CheckByTrue();
            }
            else
            {
                CheckByFasle();
            }
        }

        private void btnSaveJob_Click(object sender, EventArgs e)
        {
            SaveNewJob();
        }

        private void sC_IDGridLookUpEdit1_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                objJob.ServiceCode = BaseDAL.DB.ServiceCodes.Single(c => c.SC_ID == (int)e.NewValue);
            }
            catch { }
        }
        #endregion


        #region Part  in job

        // Khai báo trạng thái mặc định 
        private Status statusPartJob = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private JobPart jpart = new JobPart();
        
        //Hiển thị số thứ tự của gridview
        private void gridViewPJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void repositoryItemGridLookUpEdit5_EditValueChanged(object sender, EventArgs e)
        {
            gridView15.PostEditor();
        }

        private void repositoryItemGridLookUpEdit6_EditValueChanged(object sender, EventArgs e)
        {
            gridView15.PostEditor();
        }

        private void gridView15_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                repositoryItemGridLookUpEdit5.ReadOnly = true;
                repositoryItemGridLookUpEdit6.ReadOnly = true;
            }
            else
            {
                repositoryItemGridLookUpEdit5.ReadOnly = false;
                repositoryItemGridLookUpEdit6.ReadOnly = false;
            }
        }

        private void DeletePartJob(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                jpart = jobPartBindingSource.Current as JobPart;
                if (jpart.Job_ID != 0)
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(jpart.Job_ID);
                    if (objWorkOrder != null)
                    {
                        PartWorkOrder partWorkOrder = new PartWorkOrder();

                        partWorkOrder.Parts_ID = jpart.Parts_ID;
                        partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                        partWorkOrder.Quantity = jpart.Quantity;

                        PartWorkOrder_BLL.Delete(partWorkOrder);
                    }

                    bool result = PartJob_BLL.Delete(jpart);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        e.Handled = true;
                    }
                    jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(objJob.Job_ID, true);
                }
                else
                {
                    jobPartBindingSource.RemoveCurrent();
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        // Sự kiện nhân phím delete sảy ra
        private void gridViewPJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                jpart = jobPartBindingSource.Current as JobPart;
                if (jpart.Job_ID != 0)
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(jpart.Job_ID);
                    if (objWorkOrder != null)
                    {
                        PartWorkOrder partWorkOrder = new PartWorkOrder();

                        partWorkOrder.Parts_ID = jpart.Parts_ID;
                        partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                        partWorkOrder.Quantity = jpart.Quantity;

                        PartWorkOrder_BLL.Delete(partWorkOrder);
                    }

                    bool result = PartJob_BLL.Delete(jpart);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        e.Handled = true;
                    }
                    jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(objJob.Job_ID, true);
                }
                else
                {
                    jobPartBindingSource.RemoveCurrent();
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewPJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            jpart.Job_ID = 0;
            statusPartJob = Status.New;
            GridView view = (GridView)sender;

            GridColumn Quantity = view.Columns["Quantity"];
            view.SetRowCellValue(e.RowHandle, Quantity, 0);

            GridColumn PartCode = view.Columns["Parts_ID"];
            view.SetRowCellValue(e.RowHandle, PartCode, 0);

        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewPJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (null != objJob)
            {
                GridView view = (GridView)sender;
                GridColumn PartCode = view.Columns[1];
                GridColumn PartName = view.Columns[2];
                if (0 == int.Parse(view.GetRowCellValue(e.RowHandle, PartCode).ToString()))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part ";
                    view.SetColumnError(PartCode, "Part is not empty");
                    view.SetColumnError(PartName, "Part is not empty");
                }
                JobPart jp = new JobPart();
                jp.Parts_ID = jpart.Parts_ID;
                jp.Job_ID = objJob.Job_ID;

                if (PartJob_BLL.isExits(jp) && statusPartJob != Status.Update)
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Part is exits. ";
                    view.SetColumnError(PartCode, "Part is exits");
                    view.SetColumnError(PartName, "Part is exits");
                }
            }
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewPJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl3.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(objJob.Job_ID, true);
                    statusPartJob = Status.Update;
                }
            }

        }
        // Đặt lại trạng thái update 
        private void gridViewPJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusPartJob = Status.Update;
            }
        }

        #endregion

        private void jobPartBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            jpart = jobPartBindingSource.Current as JobPart;
        }

        #region Attachment Job

        // Khai báo trạng thái mặc định 
        private Status statusAttachmentJob = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private AttachmentsJob attachmentJob = new AttachmentsJob();
        //Hiển thị số thứ tự của gridview

        private void gridViewAJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void attachmentsJobBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedAJ = true;
        }


        private void attachmentsJobBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            attachmentJob = attachmentsJobBindingSource.Current as AttachmentsJob;
        }

        private void btnOpenFileJob_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenDocumentAJ();
            }
            catch { }
        }

        private void btnUploadFileAJ_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {

                    string extension = Path.GetExtension(fileName);
                    attachmentJob.Extentsion = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    attachmentJob.ContentFile = fileBinary;
                    GridColumn AttachExtension = gridView13.Columns["Extentsion"];
                    extension = extension.ToUpper();
                    gridView13.SetRowCellValue(gridView13.FocusedRowHandle, AttachExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }

        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewAJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
          //  SaveAttachmentJobToDatabase();
        }

        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Office 2007 Blue");
            }
        }

        private void DeleteAttachmentJob(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (attachmentJob.Attachment_ID != 0)
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(attachmentJob.Job_ID.Value);
                    if (objWorkOrder != null)
                    {
                        AttachmentWorkOrder_BLL.DeleteByID(attachmentJob.Attachment_ID);
                    }
                    bool result = AttachmentJob_BLL.Delete(attachmentJob);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        e.Handled = true;
                    }
                    attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(objJob.Job_ID, isChangedAJ);
                    isChangedAJ = false;
                }
                else
                {
                    attachmentsJobBindingSource.RemoveCurrent();
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        // Sự kiện nhân phím delete sảy ra
        private void gridViewAJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (attachmentJob.Attachment_ID != 0)
                    {
                        bool result = AttachmentJob_BLL.Delete(attachmentJob);
                        if (!result)
                        {
                            XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            e.Handled = true;
                        }
                        attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(objJob.Job_ID, isChangedAJ);
                        isChangedAJ = false;
                    }
                    else
                    {
                        attachmentsJobBindingSource.RemoveCurrent();
                    }
                }
                else
                {
                    e.Handled = true;
                }
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewAJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            statusAttachmentJob = Status.New;
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewAJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (null != objJob)
            {
                GridView view = (GridView)sender;
                GridColumn AttachName = view.Columns["Name"];
                GridColumn AttachCode = view.Columns["Code"];
                GridColumn AttachContent = view.Columns["ContentFile"];

                if (null == view.GetRowCellValue(e.RowHandle, AttachName))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachName;
                    e.ErrorText = "Please enter the Attachment Name. ";
                    view.SetColumnError(AttachName, "Attachment Name is not empty");
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Please enter the Attachment Code. ";
                    view.SetColumnError(AttachCode, "Attachment Code is not empty");
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
                {
                    e.Valid = false;
                    e.ErrorText = "Please upload one file into table ";
                }
                AttachmentsJob attach = attachmentJob;
                attach.Job_ID = objJob.Job_ID;

                if (AttachmentJob_BLL.IsExits(attach))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Attachment Code is exits. ";
                    view.SetColumnError(AttachCode, "Attachment Code is exits");
                }
            }
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewAJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl17.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(objJob.Job_ID, isChangedAJ);
                    isChangedAJ = false;
                }
            }
        }

        // Đặt lại trạng thái update 
        private void gridViewAJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusAttachmentJob = Status.Update;
            }
        }

        private void OpenDocumentAJ()
        {
            if (gridView13.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                if (attachmentJob.Attachment_ID != 0)
                {
                    AttachmentsJob attach = AttachmentJob_BLL.GetDataById(attachmentJob.Attachment_ID);
                    if (null != attach)
                    {
                        string fileName = attach.Name + attach.Extentsion;
                        Address += fileName;
                        if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                        {
                            try
                            {
                                Process.Start(Address);
                            }
                            catch
                            {
                                XtraMessageBox.Show("Can't open file", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }

                    }
                }
                else
                {
                    string fileName = attachmentJob.Name + attachmentJob.Extentsion;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attachmentJob.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch
                        {
                            XtraMessageBox.Show("Can't open file", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }
        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            return false;
        }

        #endregion

        private void jobBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (objJob != null)
            {
                ucRichEditControl1.richEditControl1.Text = objJob.Details;
            }
        }

        private void repositoryItemGridLookUpEdit5_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                ((JobPart)gridView15.GetFocusedRow()).PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(c => c.Parts_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void repositoryItemGridLookUpEdit6_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                ((JobPart)gridView15.GetFocusedRow()).PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(c => c.Parts_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void freodicFrequencyTextEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void timeDoneTextEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void alarmDaybeforeTextEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void employee_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                objJob.Employee = BaseDAL.DB.Employees.Single(c => c.Employee_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveNewJob();
        }

        private void gridControl3_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    DeletePartJob(e);
                    break;
            }
        }

        private void gridControl17_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    DeleteAttachmentJob(e);
                    break;
            }
        }
    }

}